import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:lib_core/lib_core.dart';

class AuthService extends GetxService {
  static AuthService get to => Get.find();

  final _kv = GetStorage();
  final _kvUser = 'lastUser';
  final _kvAccount = 'lastAccount';
  UserModel? _oldUser;
  final Rx<UserModel?> user = Rx(null);

  Future<AuthService> init() async {
    // 监听user更新
    _listenUser();
    _checkUser();
    return this;
  }

  void _listenUser() {
    user.listen((newValue) {
      // 同步给原生
      // UserHostApi().updateUser(newValue?.toJsonStr());
      if (newValue != null && _oldUser == null) {
        // 登录
        _handleLogin(newValue);
      } else if (newValue == null && _oldUser != null) {
        // 登出
        _handelLogout();
      }
    });
  }

  void _handleLogin(UserModel model) {
    _oldUser = model;
    // 获取全局保存的数据
  }

  void _handelLogout() {
    _oldUser = null;
    // 清楚其他本地数据
  }

  void _checkUser() async {
    final cachedUser = getCachedUser();
    user.value = cachedUser;
    if (cachedUser != null) {
      // 如果有刷新token的接口，可以在这里处理
    }
  }

  UserModel? getCachedUser() {
    final json = _kv.read(_kvUser);
    debugPrint('getCachedUser:$json');

    UserModel? user;
    if (json != null) {
      try {
        user = UserModel.fromJson(json);
      } catch (e) {
        e.printError();
        user = null;
      }
    }
    return user;
  }

  void saveUser(UserModel model) {
    this.user.value = model;
    cacheUser(model);
  }

  void cacheUser(UserModel model) {
    _kv.write(_kvUser, model);
  }

  void clearUser() {
    user.value = null;
    clearCacheUser();
  }

  void clearCacheUser() {
    _kv.remove(_kvUser);
  }

  void cacheAccount(String account) {
    _kv.write(_kvAccount, account);
  }

  String? get lastAccount => _kv.read(_kvAccount);

  void logout(VoidCallback onSuccess) {
    clearUser();
    onSuccess.call();
  }


}
